package com.literature.search.file.service.impl;

import com.literature.search.core.common.MessageConstant;
import com.literature.search.core.entity.DownloadRecord;
import com.literature.search.core.entity.R.AjaxJson;
import com.literature.search.core.entity.dto.BasePageDTO;
import com.literature.search.core.utils.ObjectUtil;
import com.literature.search.core.utils.so.SoMap;
import com.literature.search.core.utils.sp.SpUserUtil;
import com.literature.search.file.entity.vo.DownloadRecordVO;
import com.literature.search.file.service.DownloadRecordService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName DownloadRecordServiceImpl
 * @Description TODO
 * @Author abin
 * @Date 2023/3/2 20:59
 * @Version 1.0
 */
@Service
public class DownloadRecordServiceImpl implements DownloadRecordService {
    public static final String DOWNLOAD_RECORD_COLLECTION_NAME = "download_record";//集合名称

    public static final String USER_ID = "user_id";//用户Id

    public static final String DOWNLOAD_DATE = "download_date";//下载日期

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public AjaxJson findDownloadRecordByUserId(BasePageDTO page) {
        long count = mongoTemplate.count(new Query(Criteria.where(USER_ID).is(SpUserUtil.getCurrUser().getId())), DownloadRecord.class, DOWNLOAD_RECORD_COLLECTION_NAME);
        if (count < 1) {
            return AjaxJson.getError(MessageConstant.DATA_IS_NULL);
        }
        int pageNum = Optional.ofNullable(page.getPage()).orElse(1);
        int pageSize = Optional.ofNullable(page.getRows()).orElse(10);
        // 如果传入的参数超过了总数，返回第一页
        if ((long) (pageNum - 1) * pageSize > count) {
            pageNum = 1;
        }
        Query query = new Query();
        query.skip((long) (pageNum - 1) * pageSize);
        query.limit(pageSize);
        query.with(Sort.by(Sort.Direction.DESC,DOWNLOAD_DATE));
        List<DownloadRecord> list = mongoTemplate.find(query, DownloadRecord.class, DOWNLOAD_RECORD_COLLECTION_NAME);

        List<DownloadRecordVO> records = new ArrayList<>();
        list.stream().forEach(downloadRecord -> {
            DownloadRecordVO recordVO = new DownloadRecordVO();
            recordVO.setFileName(downloadRecord.getFileName());
            recordVO.setUserName(downloadRecord.getUserName());
            recordVO.setDownloadDate(downloadRecord.getDownloadDate());
            records.add(recordVO);
        });

        SoMap map = new SoMap();
        map.put("total", count);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("result", records);
        return AjaxJson.getSuccessData(map);
    }

    @Override
    public AjaxJson deleteDownloadRecordById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        boolean isExist = mongoTemplate.exists(query,DownloadRecord.class,DOWNLOAD_RECORD_COLLECTION_NAME);
        if (!isExist){
            AjaxJson.getError(MessageConstant.OPERATE_FAILED);
        }
        mongoTemplate.remove(query,DOWNLOAD_RECORD_COLLECTION_NAME);
        return AjaxJson.getSuccess(MessageConstant.SUCCESS);
    }

    @Override
    public boolean insertDownloadRecord(DownloadRecord record) {
        List<String> excludeFieldNames = new ArrayList<>();
        excludeFieldNames.add("_id");
        if (ObjectUtil.checkObjFieldsIsNotNull(record,excludeFieldNames)){
            mongoTemplate.save(record,DOWNLOAD_RECORD_COLLECTION_NAME);
            return true;
        }
        return false;
    }

}
